/*
 * @Author: luqinghua
 * @Date: 2025-06-11 11:30:50
 * @LastEditors: luqinghua
 * @LastEditTime: 2025-06-11 15:48:41
 * @FilePath: \express-api-example\src\apitest.ts
 * @Description: 
 */
import express, { Request, Response, NextFunction } from 'express';
import SQLiteUtils from './sqlite';

// 定义用户数据结构
interface User {
  id?: number;
  name: string;
  email: string;
}

// 创建 API 路由的函数，接收 express 实例和 SQLite 工具类实例
export function setupApiRoutes(app: express.Application, dbUtils: SQLiteUtils) {
  // 获取所有用户
  app.get('/api/getUsers', async (req: Request, res: Response, next: NextFunction) => {
    try {
      const users = await dbUtils.all('SELECT  * from  users');
      if (!users || users.length === 0) {
        return res.status(404).json({ message: '没有找到用户' });
      }
      res.json(users);
    } catch (err) {
      next(err);
    }
  });

  // 添加新用户
  app.post('/api/users', async (req: Request, res: Response, next: NextFunction) => {
    try {
      const { name, email } = req.body as User;
      if (!name || !email) {
        throw new Error('姓名和邮箱为必填项');
      }
      const result = await dbUtils.run('INSERT INTO users (name, email) VALUES (?,?)', [name, email]);
      const newUser: User = { id: result.lastID, name, email };
      res.status(201).json(newUser);
    } catch (err) {
      next(err);
    }
  });

  // 错误处理中间件（可根据需要细化错误返回格式等）
  app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
    console.error('API 错误:', err.message);
    res.status(500).json({ error: err.message });
  });
}
// import express from 'express';

// const app = express();
// const port = process.env.PORT || 3000;

// // API 路由
// app.get('/api/getUser', (req, res) => {
//   const user = {
//     name: "张三",
//     age: 19
//   };
//   res.json(user);
// });

// // 启动服务器
// app.listen(port, () => {
//   console.log(`服务器运行在 http://localhost:${port}`);
// });
